//
//  LoadingView.swift
//  ClassManager
//
//  Created by qh w on 2021/3/6.
//

import SwiftUI

struct LoadingView<Content: View>: View {
    @State var load = false
    @ViewBuilder var content: () -> Content
    @State var useBiometryProtect = false
    @State var once = false
    @State var classChoosable = false
    @StateObject var ClassName = ClassNameData()
    @State var finished = false
    @State var newClassName = ""
    @State var timeOut = 0
    @State var timer = Timer.TimerPublisher(interval: 5, runLoop: .current, mode: .default).autoconnect()
    @State var showWarning = false
    @State var showError = false
    @State var showSetting = false
    @State var errorStr = ""
    @State var selection: UUID? = nil
    @State var isEditing = false
    @State var selectedIndex: [UUID:Bool] = [:]
    @State var ERRAController: UIAlertController = UIAlertController()
    @Environment(\.scenePhase) var scenePhase
    @Environment(\.colorScheme) var _Color
    var body: some View {
        DispatchQueue.main.async {
            if !once {
                once  = true
                RunAfterVierified(skip: !useBiometryProtect) {
                    load = true
                    ClassName.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                }
                _ = ClassName.downloadDataByHttp()
                if !useBiometryProtect {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        load = true
                        ClassName.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                    }
                }
            }
        }
        if !ClassName.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG
        {
            DispatchQueue.main.async {
                withAnimation(.default) {
                    finished = true
                }
            }
        }
        return ZStack {
            if !load {
                ZStack {
                    VStack {
                        Image("launcher").cornerRadius(5)
                        Text("课程管理系统")
                            .font(.largeTitle)
                            .bold()
                        HStack {
                            Text("2023 Autumn")
                                .font(.title)
                            Divider()
                            Text("Beta")
                                .font(.title)
                                .foregroundColor(.green)
                        }.frame(height: 20)
                    }.frame(height: 100)
                    if useBiometryProtect {
                        VStack {
                            Spacer()
                            RoundedRectangle(cornerRadius: 10)
                                .foregroundColor(.init("blue"))
                                .frame(width: 200, height: 40)
                                .overlay(Text("解锁").foregroundColor(.white))
                                .onTapGesture {
                                    RunAfterVierified {
                                        load = true
                                        ClassName.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                                    }
                                }
                                .padding(.bottom)
                        }
                    }
                }
            }
            if load {
                ZStack {
                    NavigationView {
                        if finished {
                            ScrollView {
                                VStack {
                                    ForEach(ClassName.ClassName) { _className in
                                        if !_className.isDeleted {
                                            Fluent_Rect {
                                                VStack {
                                                    SingleClassroomCard(_className: _className, selectedIndex: $selectedIndex, showWarning: $showWarning, selection: $selection)
                                                        .environmentObject(ClassName)
                                                    if selectedIndex[_className.id] == true {
                                                        Divider().padding(.horizontal)
                                                        // MARK: Remove class
                                                        HStack {
                                                            Button(action: {
                                                                RunAfterVierified {
                                                                    for idx in 0..<self.ClassName.ClassName.count {
                                                                        if ClassName.ClassName[idx].id == _className.id {
                                                                            withAnimation(.spring) {
                                                                                self.ClassName.ClassName[idx].isDeleted = true
                                                                            }
                                                                            break
                                                                        }
                                                                    }
                                                                    _ = ClassName.uploadDataByHttp()
                                                                }
                                                            }) {
                                                                Image(systemName: "trash.fill")
                                                                    .imageScale(.large)
                                                                    .foregroundColor(.red)
                                                            }
                                                            .disabled(!useBiometryProtect)
                                                            Spacer()
                                                        }
                                                        .padding([.horizontal, .bottom])
                                                    }
                                                }
                                            }
                                            .frame(height: selectedIndex[_className.id] == true ? 170:100)
                                            .transition(.slide)
                                            .onTapGesture(perform: {
                                                if !classChoosable {
                                                    return
                                                }
                                                withAnimation(.spring()) {
                                                    if self.selectedIndex[_className.id] == true {
                                                        self.selectedIndex[_className.id] = false
                                                        return
                                                    }
                                                    self.selectedIndex = [_className.id:true]
                                                }
                                            })
                                        }
                                    }
                                    if classChoosable {
                                        Fluent_Rect {
                                            VStack {
                                                HStack {
                                                    TextField("新班级", text: self.$newClassName, onEditingChanged: { change in
                                                        if change {
                                                            withAnimation(.spring()) {
                                                                self.isEditing = true
                                                            }
                                                            print("LodingView.swift/TextField: changed", Date())
                                                        }
                                                    }, onCommit: {
                                                        withAnimation(.spring()) {
                                                            self.isEditing = false
                                                        }
                                                        print("LodingView.swift/TextField: commit", Date())
                                                    })
                                                        .foregroundColor(.white)
                                                    Spacer()
                                                    Button(action: {
                                                        print(newClassName)
                                                        withAnimation(.spring) {
                                                            ClassName.ClassName.append(className(name: self.newClassName))
                                                        }
                                                        _ = ClassName.uploadDataByHttp()
                                                        _ = CoreData(classNameStr: newClassName).uploadDataByHttp()
                                                        self.newClassName = ""
                                                    }) {
                                                        Fluent_Rect(ForeGroundColor: .green) {
                                                            Image(systemName: "plus")
                                                                .imageScale(.large)
                                                                .foregroundColor(.white)
                                                        }
                                                        .frame(width: 90, height: 85)
                                                    }
                                                }
                                                .padding(isEditing ? [.top, .leading]:[.vertical, .leading])
                                                if isEditing {
                                                    Divider()
                                                        .padding(.horizontal)
                                                    HStack {
                                                        Button(action: {
                                                            withAnimation(.spring()) {
                                                                self.isEditing = false
                                                            }
                                                            UIApplication.shared.windows.forEach({ window in
                                                                if window.isKeyWindow {
                                                                    window.endEditing(true)
                                                                }
                                                            })
                                                        }) {
                                                            Image(systemName: "keyboard.chevron.compact.down")
                                                                .foregroundColor(.white)
                                                                .imageScale(.large)
                                                            
                                                        }
                                                        .foregroundColor(Color("Default"))
                                                        Spacer()
                                                    }
                                                    .padding([.horizontal, .bottom])
                                                }
                                            }
                                        }
                                        .frame(height: isEditing ? 170:100)
                                    }
                                    Spacer()
                                }
                                
                            }
                            .navigationBarTitle("所有班级")
                            .navigationBarItems(leading: Button(action: {
                                showSetting = true
                            }) {
                                Image(systemName: "gear")
                                    .imageScale(.large)
                            })
                            
                        }
                        else {
                            List {
                                HStack {
                                    Text("正在加载...")
                                    Spacer()
                                    ProgressView()
                                        .progressViewStyle(CircularProgressViewStyle())
                                }
                                if classChoosable {
                                    Button(action: {
                                        RunAfterVierified {
                                            _ = ClassNameData().uploadDataByHttp()
                                        }
                                    }) {
                                        Text("初始化")
                                            .foregroundColor(.red)
                                    }
                                }
                                Button(action: {
                                    showSetting = true
                                }, label: {
                                    Text("软件设置")
                                })
                            }
                        }
                    }
                    .sheet(isPresented: self.$showSetting) {
                        NavigationView {
                            SettingsView(showCloseButton: true)
                        }
                    }
                    .navigationBarHidden(false)
                    .navigationViewStyle(StackNavigationViewStyle())
                    .background(SUIAController(showAlert: $showError, $ERRAController))
                    .onReceive(timer, perform: { _ in
                        if !load {
                            return
                        }
                        self.showWarning = ClassName.FILE_PROVIDER_IS_UPLOADING_FLAG
                        // print(ClassName.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG)
                        if ClassName.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG {
                            timeOut += 1
                        }
                        if timeOut == 2 {
                            timeOut = 0
                            connect()
                        }
                        // print("FILE_DOWNLOAD_ISNOT_FINISHED_FLAG:\(ClassName.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG)")
                        if !ClassName.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG {
                            self.finished = true
                            connect()
                            if let error = ClassName.fileProviderError {
                                let error = error as NSError
                                // print("errorCode: \(error.code)\n----------\n")
                                self.errorStr = error.localizedDescription + "\nPlease reopen the app or contact with your adiministrator for further help."
                                //                                self.showError = true
                                ClassName.fileProviderError = nil
                                self.timer = Timer.TimerPublisher(interval: 120, runLoop: .current, mode: .default).autoconnect()
                                ERRAController = UIAlertController(title: "出现网络错误", message: errorStr, preferredStyle: .alert)
                                ERRAController.message = errorStr
                                ERRAController.addAction(UIAlertAction(title: "转到设置", style: .default) { _ in
                                    showSetting = true
                                })
                                ERRAController.addAction(UIAlertAction(title: "重试", style: .destructive, handler: { _ in
                                    self.timer = Timer.TimerPublisher(interval: 5, runLoop: .current, mode: .default).autoconnect()
                                }))
                                showError = true
                            }
                        }
                    })
                    
                }
            }
        }
        .onChange(of: self.scenePhase) { _ in
            if scenePhase == .background && useBiometryProtect {
                DispatchQueue.main.async {
//                    exit(0)
                    self.once = false
                    self.load = false
                }
            }
        }
    }
    private func connect() {
        _ = ClassName.downloadDataByHttp()
    }
}

struct Fluent_Rect<Content>: View where Content: View {
    @State var ForeGroundColor: Color = .blue
    @ViewBuilder var content: () -> Content
    @Environment(\.colorScheme) var uiAppearance
    var body: some View {
        Rectangle()
            .foregroundColor(ForeGroundColor)
            .cornerRadius(20)
            .opacity(0.5)
            .padding()
            .overlay(content().padding())
    }
}

struct SingleClassroomCard: View {
    @EnvironmentObject var ClassName: ClassNameData
    @State var _className: className
    @State var allowBLE: Bool = false
    @Binding var selectedIndex: [UUID:Bool]
    @Binding var showWarning: Bool
    @Binding var selection: UUID?
    var body: some View {
        DispatchQueue.main.async {
            allowBLE = _className.BLEName != nil
        }
        return VStack {
            HStack {
                Text(_className.name)
                    .bold()
                    .font(.title)
                    .foregroundColor(.white)
                    .padding(.leading)
                if allowBLE {
                    Divider()
                        .padding(.vertical)
                    Image(systemName: "wave.3.backward")
                        .foregroundColor(.white)
                    Text("无线打卡已开启")
                        .foregroundColor(.white)
                }
                Spacer()
                NavigationLink(destination: ContentView(UserData: CoreData(classNameStr: _className.name), showWarning: $showWarning).environmentObject(ClassName), tag: _className.id, selection: $selection) {
                    Button(action: {
                        selection = _className.id
                        ClassName.IS_INTERNET_OPERATION_ALLOWED_FLAG = false
                    }) {
                        Fluent_Rect(ForeGroundColor: .green) {
                            Image(systemName: "chevron.right")
                                .imageScale(.large)
                                .foregroundColor(.white)
                        }
                        .frame(width: 90, height: 85)
                    }
                }
            }
        }
    }
}
